﻿using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System.Text;

namespace RabbitMQTest
{
    internal class Program
    {
        private const string DELAY_EXCHANGE_NAME = "test_delay_exchange";
        private const string ROUTE_KEY = "test_routekey";
        private const string EXCHANGE_NAME = "test_exchange";
        private const string QUEUE_NAME = "test_queue";

        static void Main(string[] args)
        {
            ConnectionFactory factory = new ConnectionFactory()
            {
                HostName = "1.13.255.149",
                Port = 5672,
                UserName = "wau",
                Password = "wska7LkYi2yMA",
                VirtualHost = "/wau"
            };

            Task.Run(() => 
            {
                ReceiveDelayMsgs(factory);
            });

            Console.ReadLine();
        }

        private static void ReceiveDelayMsgs(ConnectionFactory factory)
        {
            var connection = factory.CreateConnection();
            var channel = connection.CreateModel();

            // 声明延迟交换机的类型（与默认的交换机类型相同）
            Dictionary<string, object> exchangeParamsDic = new Dictionary<string, object>
                {
                    { "x-delayed-type", "direct" }
                };

            // 声明延迟交换机（如果没有则自动创建）
            channel.ExchangeDeclare(DELAY_EXCHANGE_NAME, "x-delayed-message", true, false, exchangeParamsDic);
            channel.QueueBind(QUEUE_NAME, DELAY_EXCHANGE_NAME, "");

            var consumer = new EventingBasicConsumer(channel);
            consumer.Received += (sender, args) =>
            {
                Console.WriteLine($"收到了消息 {Encoding.UTF8.GetString(args.Body.ToArray())}，当前时间为：{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}");
                channel.BasicAck(args.DeliveryTag, false);
            };
            channel.BasicConsume(QUEUE_NAME, false, consumer);
        }
    }
}